package handler

import (
	"github.com/gin-gonic/gin"
	"github.com/goccy/go-json"
	"recruit-ease/cache"
	"recruit-ease/model"
	"strconv"
	"time"
)

func List(c *gin.Context) {
	page, _ := strconv.Atoi(c.DefaultQuery("page", "1"))
	size, _ := strconv.Atoi(c.DefaultQuery("size", "3"))
	offset := (page - 1) * size
	var idea []model.Idea
	redis_key := "idea_list" + strconv.Itoa(page)
	cacheData, _ := cache.Rdb.Get(cache.Ctx, redis_key).Result()
	if cacheData == "" {
		model.DB.Offset(offset).Limit(size).Find(&idea).Debug()
		jsonData, _ := json.Marshal(idea)
		cache.Rdb.Set(cache.Ctx, redis_key, jsonData, time.Hour*2)
	} else {
		json.Unmarshal([]byte(cacheData), &idea)
	}
	var total int64
	model.DB.Model(&model.Idea{}).Count(&total)
	c.JSON(200, gin.H{
		"code":  200,
		"msg":   "OK",
		"data":  idea,
		"total": total,
	})
	return
}
func Detail(c *gin.Context) {
	id := c.Query("id")
	var idea model.Idea
	redis_key := "idea_detail" + id
	cacheData, _ := cache.Rdb.Get(cache.Ctx, redis_key).Result()
	if cacheData == "" {
		model.DB.Where("id=?", id).Find(&idea).Debug()
		jsonData, _ := json.Marshal(idea)
		cache.Rdb.Set(cache.Ctx, redis_key, jsonData, time.Hour*2)
	} else {
		json.Unmarshal([]byte(cacheData), &idea)
	}
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "OK",
		"data": idea,
	})
	return
}
func Like(c *gin.Context) {
	title := c.PostForm("title")
	comment := c.PostForm("comment")
	address := c.PostForm("address")
	data := model.Idea{
		Title:   title,
		Comment: comment,
		Address: address,
	}
	err := model.DB.Create(&data).Debug().Error
	if err != nil {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "收藏失败",
		})
		return
	}
	var idea model.Idea
	redis_key := "idea_like"
	model.DB.Where("id=?", data.ID).Find(&idea)
	jsonData, _ := json.Marshal(idea)
	cache.Rdb.Set(cache.Ctx, redis_key, jsonData, time.Hour*2)
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "收藏成功",
	})
	return
}
